﻿using System;
using System.IO;
using System.Xml;
using System.Data.OracleClient;
using TimeTableEasy.src.Database;

namespace TimeTableEasy.src.Core
{
    class Offline
    {

        private static XmlDocument XMLFile = new XmlDocument();

        public Offline()
        {            
        }

        public static bool IsAccount(UInt32 id)
        {
            XMLFile.Load("saves/users.xml");
            XmlNodeList nodelist = XMLFile.SelectNodes("Users/user");
            foreach (XmlNode xn in nodelist)
                if (UInt32.Parse(xn["ID"].InnerText) == id)
                    return true;

            return false;
        }

        public static bool CheckPassword(UInt32 id, String password)
        {
            XMLFile.Load("saves/users.xml");
            XmlNodeList nodelist = XMLFile.SelectNodes("Users/user");
            foreach (XmlNode xn in nodelist)
                if (UInt32.Parse(xn["ID"].InnerText) == id)
                    if(xn["Hash"].InnerText.Equals(Account.CalculateShaPassHash(password)))
                        return true;

            return false;
        }

        public static void SaveUser()
        {
            try
            {
                if(!Directory.Exists("saves"))
                   Directory.CreateDirectory("saves");
            }
            catch (Exception ex)
            {
                LogMgr.ERROR_LOG("OFFLINE MODE ERROR : "+ex.Message);
            }

            try
            {
                if(File.Exists("saves/users.xml"))
                    File.Delete("saves/users.xml"); 

                XmlDocument User_Xml = new XmlDocument();
                User_Xml.AppendChild(User_Xml.CreateXmlDeclaration("1.0", "utf-8", ""));
                XmlNode racine = User_Xml.CreateNode(System.Xml.XmlNodeType.Element, "Users", "");
                User_Xml.AppendChild(racine);

                OracleDataReader array = OracleConnector.Query("SELECT IDE_ID,IDE_MDP FROM IDENTITE");

                if (array == null) return;

                while (array.Read())
                {
                    XmlNode noeud = User_Xml.CreateElement("user");
                    XmlNode ID = User_Xml.CreateElement("ID");
                    ID.InnerText = array.GetDecimal(0).ToString();
                    noeud.AppendChild(ID);
                    XmlNode Hash = User_Xml.CreateElement("Hash");
                    Hash.InnerText = array.GetString(1);
                    noeud.AppendChild(Hash);

                    racine.AppendChild(noeud);
                }
                User_Xml.Save("saves/users.xml");
            }
            catch (Exception ex)
            {
                LogMgr.DEBUG_LOG(ex.Message);
            }


        }

    }
}
